﻿using System;
using System.Collections.Generic;
using RentalSystem.Data.EF.Core;

namespace RentalSystem.Data.EF.Dao
{
    public class EFSettingsDao : ISettingsDao
    {
        #region Queries

        private static string GetQuery;
        private static string ListQuery;

        #endregion

        private EFManager<Settings> manager;

        public EFSettingsDao(RentalDatabaseEntities repository)
        {
            GetQuery = "SELECT VALUE s FROM Settings AS s WHERE s.SettingKey = @Key;";
            ListQuery = "SELECT VALUE s FROM Settings AS s;";

            this.manager = new EFManager<Settings>(repository);
        }

        #region IDao1Key

        public Settings Add(Settings entity)
        {
            manager.Database.AddToSettings(entity);
            manager.Save();
            return entity;
        }

        public Settings Get(string key)
        {
            QueryParam[] parameters = new QueryParam[]
                {
                    new QueryParam("@Key", key)
                };

            var settings = manager.SQLQueryToEntity(GetQuery, parameters);

            foreach (Settings setting in settings)
            {
                return setting;
            }

            return null;
        }

        public void Delete(string key)
        {
            manager.Database.Settings.DeleteObject(Get(key));
            manager.Save();
        }

        public void Delete(Settings entity)
        {
            if (entity != null)
                Delete(entity.SettingKey);
        }

        public void Update(Settings entity, uint fields)
        {
            if (entity == null)
                return;

            Settings fromDb = Get(entity.SettingKey);

            if (fromDb == null)
                throw new ArgumentException("Podany klucz ustawień nie występuje w bazie");

            fromDb.SettingValue = entity.SettingValue;
            manager.Save();
        }

        public List<Settings> List()
        {
            throw new NotImplementedException();
        }

        #endregion

        public Dictionary<string, string> AllSettings()
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            var settings = manager.SQLQueryToEntity(ListQuery);

            foreach (Settings setting in settings)
            {
                result.Add(setting.SettingKey, setting.SettingValue);
            }

            return result;
        }
    }
}
